import * as React from 'react';

import { Table, Button, Divider, message } from 'antd';
import { requestGetFault, GetFaultReturnData, requestDeleteFault } from '../../api';
import { RouteComponentProps } from 'react-router';
import errorHandler from '../../api/utils/requestErrorHandler';
import './index.css';

type Props = RouteComponentProps;
const { useEffect, useState } = React;

const FaultList = (props: Props): JSX.Element => {
  const [list, setList] = useState<GetFaultReturnData[]>([]);

  const fetchData = (): void => {
    requestGetFault().then(({ data }) => {
      setList(data);
    });
  };

  useEffect(() => {
    fetchData();
  }, []);

  const edit = ({ _id }: GetFaultReturnData): void => {
    props.history.push(`/edit/${_id}`, { mode: 'edit' });
  };

  const remove = ({ _id }: GetFaultReturnData): void => {
    requestDeleteFault(_id)
      .then(() => {
        message.success('删除成功');
        fetchData();
      })
      .catch((err) => {
        errorHandler(err);
      });
  };

  const create = (): void => {
    props.history.push('/add', { mode: 'add' });
  };

  const columns = [
    {
      title: '现象',
      dataIndex: 'name',
      key: 'name'
    },
    {
      title: '操作',
      key: 'action',
      // eslint-disable-next-line react/display-name
      render: (_text: string, row: GetFaultReturnData): JSX.Element => (
        <span>
          <Button onClick={() => edit(row)}>编辑</Button>
          <Divider type="vertical" />
          <Button onClick={() => remove(row)} type="danger">
            删除
          </Button>
        </span>
      )
    }
  ];

  return (
    <div className="page">
      <div className="action-area">
        <Button type="primary" size="large" onClick={() => create()}>
          创建
        </Button>
      </div>
      <Table
        rowKey={(row) => row._id}
        columns={columns}
        dataSource={list}
        pagination={{ pageSize: 40 }}
      />
    </div>
  );
};

export default FaultList;
